﻿using Basic.UserCollect;
using Basic.UserExtendService;
using Basic.UserLocalEvent;
using Basic.UserModel.LoginLog;
using Basic.UserModel.User;
using Basic.UserRemoteModel;
using Basic.UserRemoteModel.User.Model;
using Basic.UserService.Interface;

namespace Basic.UserService.Extend
{
    internal class MiniUserRegService : IMiniUserRegService
    {
        private readonly IUserConfig _Config;

        private readonly IUserCollect _User;

        private readonly ISaveLoginLog _LoginLog;
        private readonly IFileService _File;

        public MiniUserRegService (IUserConfig config,
            IUserCollect user,
            ISaveLoginLog loginLog,
            IFileService file)
        {
            this._Config = config;
            this._User = user;
            this._LoginLog = loginLog;
            this._File = file;
        }

        public UserLoginResult UserReg (MiniUserReg reg)
        {
            UserAdd add = new UserAdd
            {
                LoginName = reg.Phone,
                LoginType = LoginType.手机号,
                NickName = reg.NickName,
                Pwd = this._Config.CalculatePwd(reg.Pwd),
                Phone = reg.Phone,
                RegMode = this._Config.MiniAppType,
                Sex = reg.Sex,
                UserHead = reg.UserHead,
            };
            long userId = this._User.RegUser(add);
            if (reg.FileId.HasValue)
            {
                this._File.Save(reg.FileId.Value, userId);
            }
            this._Login(userId, reg);
            return new UserLoginResult
            {
                NickName = add.NickName,
                Sex = add.Sex,
                UserHead = add.UserHead,
                UserId = userId
            };
        }
        private void _Login (long userId, MiniUserReg param)
        {
            LoginLogAdd log = new LoginLogAdd
            {
                UserId = userId,
                LogSource = this._Config.MiniAppType,
                LoginIp = param.LoginIp,
                LoginName = param.Phone,
                LoginType = LoginType.手机号,
                LoginTime = DateTime.Now,
                ThirdAppId = param.ThirdId,
                ThirdUserId = param.WxUserId,
                UserAgent = param.UserAgent,
                LogShow = string.Format("微信小程序用户登陆成功,昵称:{0}。", param.NickName)
            };
            this._LoginLog.AddLog(log);
            new WxUserBindEvent
            {
                UserId = userId,
                WxUserId = param.WxUserId
            }.AsyncPublic();
        }
    }
}
